package com.itheima.utils;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ExcelUtils {

    /**
     * 导出Excel, 单个sheet
     */
    public static void export(String sheetName,String fileName,Class clazz, List<? extends BaseRowModel> list)throws Exception{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(response.getOutputStream(), ExcelTypeEnum.XLSX,true);
        Sheet sheet = new Sheet(1,0, clazz); // 从第一个sheet,0行开始写入
        sheet.setSheetName(sheetName);
        sheet.setAutoWidth(Boolean.TRUE);  // 设置自适应宽度
        writer.write(list,sheet);
        writer.finish();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition","attachment;filename="+fileName + ".xlsx");
        outputStream.close();
    }
}
